package com.itstudy.interceptors;

import com.itstudy.pojo.Result;
import com.itstudy.utils.JwtUtil;
import com.itstudy.utils.ThreadLocalUtil;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("Authorization");

        try {
            ValueOperations<String,String> operations=stringRedisTemplate.opsForValue();
            operations.get(token);
            if (operations == null) {
                throw new RuntimeException();
            }
            Map<String, Object> map = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(map);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
//            Result responseResult = Result.error("NOT_LOGIN");
//            //把Result对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
//            String json = JSONObject.toJSONString((Map<String, ? extends Object>) responseResult);
//            response.setContentType("application/json;charset=utf-8");
//            //响应
//            response.getWriter().write(json);
            return false;
        }

    }
}
